package com.sky.business.sys.mqtt.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.business.sys.domain.MQTTMessage;
import com.sky.business.sys.handler.exception.NoMatchHandlerException;
import com.sky.business.sys.handler.mgr.EndPointEventHandlerManager;
import com.sky.business.sys.queue.MQTTMessageQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.SimpleTimeZone;

/**
 * 终端消息监听器
 */
@Component
@Slf4j
public class LocalReportingCallbackListener implements IMqttMessageListener {

    @Autowired
    public EndPointEventHandlerManager endPointEventHandlerManager;

    public static ObjectMapper objectMapper = new ObjectMapper().setTimeZone(SimpleTimeZone.getTimeZone("GMT+8"));


    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String messageBody = new String(message.getPayload(), StandardCharsets.UTF_8);
        log.debug("接收到终端上报的消息:{}",messageBody);
        //保存到数据库
        MQTTMessageQueueConfig.offer(new MQTTMessage(MQTTMessage.Type.REPORT, messageBody));
        try {
            JsonNode rootNode = objectMapper.readTree(messageBody);
            String event = rootNode.get("event").asText();
            //处理事件
            endPointEventHandlerManager.handle(topic, messageBody, event);
        }catch (JsonProcessingException e ){
            log.error("终端上报消息json不合法,message:{}",messageBody,e);
        }catch (NoMatchHandlerException e){
            log.error("未找到事件对应处理器",e);
        }
    }
}
